package com.study.thirdpartyeventconsumer.config.web;

import com.study.thirdpartyeventconsumer.constant.BaseEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToBaseEnum<>(targetType);
    }

    private static class StringToBaseEnum<T extends BaseEnum> implements Converter<String, T> {

        private final Class<T> enumType;

        public StringToBaseEnum(Class<T> enumType) {
            this.enumType = enumType;
        }

        @Override
        public T convert(String source) {
            if (source == null || source.trim().isEmpty()) {
                return null;
            }
            source = source.trim();

            // 先判断是否是枚举名
            try {
                return (T) Enum.valueOf((Class) enumType, source);
            } catch (IllegalArgumentException e) {
                // 忽略，尝试当code解析
            }

            // 再尝试按code匹配（假设code是int）
            try {
                int code = Integer.parseInt(source);
                for (T constant : enumType.getEnumConstants()) {
                    if (constant.getCode() == code) {
                        return constant;
                    }
                }
            } catch (NumberFormatException e) {
                // 不是数字，无法识别
            }
            throw new IllegalArgumentException("Cannot convert " + source + " to " + enumType.getSimpleName());
        }
    }
}
